import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { arraysEqual, isTemplateRef } from 'ng-zorro-antd';
import { data } from 'jquery';
import { es, th } from 'date-fns/locale';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { flatten } from '@angular/compiler';
import { ExceljsService } from "./../../myService/exceljs.service";
import { log } from 'console';


@Component({
  selector: 'app-design',
  templateUrl: './design.component.html',
  styleUrls: ['./design.component.scss'],
  providers: [DatePipe],
})
export class DesignComponent implements OnInit {
  isVisible;
  isOkLoading;
  filterEsData;
  item;
  add19code;//编辑19码
  isOkLoading19Code;

  addEngineer;//添加工程师
  isOkLoadingEngineer;

  fileInfom;//显示工單对应的文件信息
  isOkLoadingfileInfom;

  isFileVisible;
  isFileOkLoading;

  public auditRemark: string = "";//审核备注
  public auditRemark2: string = "";//审核备注

  addAudit;//主管审核
  isOkLoadingAudit;
  // public auditRemark = [];
  fileStatus;//主管审核状态
  fileStatus0;//未审核
  fileStatus1;//已审核
  fileStatus2;//被退回

  clickName;//点击人名传参
  designDate;//设计期限
  first = '';//首个19码
  tail = '';//结尾19码
  newCode19;//提示已存在的19码
  show19code;//是否显示提示信息
  selectName;//选中的工程师
  objectKeys = Object.keys;
  objectValues = Object.values;
  keydanjia;
  splitJudge: string = ',';

  public isChoose: Boolean = true;//指派工程师复选框
  EngData;
  estimate_time;//预计时间

  //所有工單数据
  public tempData = [];

  //所有工件数据
  public workData = [];

  //工程师数组
  engineerDataCheckBoox2 = [];
  public engineerData;
  public engineerDataCheckBoox = []; // 创建和engineerData个数一致的数组
  public engPerson = []; // 指派工程师
  //意同tempData
  dataTemp;

  // 接收要修改的数据
  updateData;

  public unionorder: any;//"WAKS20200304ZCH002",
  public newValue: any;//"新值"
  name;//"表中栏位名称",
  id;//文件信息id

  selectData = [];
  selectName2 = [];//存放选取的两位工程师
  newArr = []; //定义空的新数组

  code19Data = [];//存放19码的数组

  public listOfData = [];//工單文件区数据

  fileName;//文件名
  filePath;//文件路径
  fileData;//得到的base64格式数据

  public workName;//下载时需补齐的文件路径
  public link;//下载链接
  unionorderer;
  code19;
  isSendVisible = false;
  ununun;
  titlett;
  searchValue;//
  searchValue2;//
  addEngineer2;//
  engineerData2;
  leix;
  sheji;
  jiagong;
  ercijiagong;
  zuzhuang;
  addprice2 = false;
  addprice3 = false;
  price2;
  price3;
  checkBoxStatus = [
    { 'title': '進行中', 'checked': true, 'select': 0 },
    { 'title': '已指派', 'checked': false, 'select': 3 },
    { 'title': '待審核', 'checked': false, 'select': 4 },
    { 'title': '退回單據', 'checked': false, 'select': 5 },
    { 'title': '已完成', 'checked': false, 'select': 1 },
    // { 'title': '已取消', 'checked': true, 'select': 2 },
  ];
  style = {
    display: 'block',
    height: '35px',
    width: '160px',
    lineHeight: '35px',
    padding: '0px 15px'
  };
  radioValue = "0";
  infom = [
    { 'value': 'ok' },
    { 'value': '格式錯誤' },
    { 'value': '時間錯誤' },
    { 'value': '標註有問題' },
    { 'value': '信息錯誤' },
    { 'value': '信息有遺漏' },
    { 'value': '信息不完整' },
    { 'value': '請補充信息' }
  ];
  checkable;//备注信息
  selectedTags: string[] = [];
  numberlist = {
    status0: "",
    status1: "",
    status3: "",
    status4: "",
    status5: "",
  }
  addprice; // 顯示單價彈框
  price;
  zjtypeof;
  zjtypelist;
  zjtypelist2;
  xinzgd = false;
  xzunion_order;
  xzname;
  xzquatity; //数量
  xzdelivery_date;//治具交期
  xzapply_person;//填单人姓名
  xzapplyDeptDIC;//申请部门负责人
  xzcharge_department;//付费部门
  xzdelivery_addr;//送货区域
  xzfactory;//厂区
  xzmachine_type;//制作方式
  gcsindex;
  allkeyp = {
    all: 0, sj: 0, jg: 0, er: 0, zj: 0
  }
  listdata2;

  // 以下数据用于指派工程师后发送邮件
  engineerJobNo = [];
  engineerMail = [];
  mailParamsForAssign = {
    "type": '',
    "WorkOrder": "",
    "factory": "",
    "name": "",
    "machine_type": "",
    "quantity": 0,
    "toolway": "",
    "delivery_date": "",
    "emp": [],
    "empAddress":[]
  };
  mailParamsForSend = {
    "type": '',
    "WorkOrder": "",
    "factory": "",
    "name": "",
    "machine_type": "",
    "quantity": 0,
    "toolway": "",
    "delivery_date": "",
    "emp": [],
    "empAddress":[]
  };

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    private datePipe: DatePipe,
    private router: Router,
    public excel: ExceljsService

  ) { }

  ngOnInit(): void {

    //获取全部数据
    this.getDoingData();
    // this.addEngineerData()
  }
  xzgd() {
    this.xinzgd = true;
  }
  xinzgdok() {
    if (this.xzunion_order) {
      if (this.xzname) {
        if (this.xzquatity) {
          if (this.xzdelivery_date) {
            if (this.xzapply_person) {
              if (this.xzapplyDeptDIC) {
                if (this.xzcharge_department) {
                  if (this.xzdelivery_addr) {
                    if (this.xzfactory) {
                      if (this.xzmachine_type) {
                        this.xzdelivery_date = this.datePipe.transform(this.xzdelivery_date, 'yyyy-MM-dd');

                        this.axios.axiosPost("AddUnionOrder", { "union_order": this.xzunion_order, "name": this.xzname, "quatity": this.xzquatity, "delivery_date": this.xzdelivery_date, "apply_person": this.xzapply_person, "applyDeptPIC": this.xzapplyDeptDIC, "charge_department": this.xzcharge_department, "delivery_addr": this.xzdelivery_addr, "factory": this.xzfactory, "machine_type": this.xzmachine_type }).then((data) => {
                          console.log(data);
                          this.xinzgdno();
                          this.getDoingData()
                        })
                      } else {
                        alert("製作方式為空值")
                      }
                    } else {
                      alert("廠區為空值")
                    }
                  } else {
                    alert("送貨區域為空值")
                  }
                } else {
                  alert("付費部門為空值")
                }
              } else {
                alert("申請部門負責人為空值")
              }
            } else {
              alert("填單人姓名為空值")
            }
          } else {
            alert("治具交期為空值")
          }
        } else {
          alert("數量為空值")
        }
      } else {
        alert("治具名稱為空值")
      }
    } else {
      alert("工聯單號為空值")
    }

  }
  xinzgdno() {
    this.xzunion_order = "";
    this.xzname = "";
    this.xzquatity = ""; //数量
    this.xzdelivery_date = "";//治具交期
    this.xzapply_person = "";//填单人姓名
    this.xzapplyDeptDIC = "";//申请部门负责人
    this.xzcharge_department = "";//付费部门
    this.xzdelivery_addr = "";//送货区域
    this.xzfactory = "";//厂区
    this.xzmachine_type = "";//制作方式
    this.xinzgd = false;

  }
  search() {
    console.log(this.searchValue);
    this.getDoingData()
  }
  reset() {
    console.log(this.searchValue);
    this.searchValue = "";
    this.getDoingData();
  }
  search2() {
    console.log(this.searchValue2);
    this.getDoingData();
  }
  reset2() {
    console.log(this.searchValue2);
    this.searchValue2 = "";
    this.getDoingData();

  }
  //查询进行中工單信息
  getDoingData() {
    this.selectData = [];
    console.log(this.radioValue);

    this.axios.axiosPost('QueryUnionOrder', { "stage": 0, "stageValue": 1, "status": this.radioValue, "order": this.searchValue, "name": this.searchValue2 })
      .then((data) => {
        if (data) {
          this.numberlist = data["status_count"]
          this.tempData = data['order'];
          this.dataTemp = this.tempData;
          // console.log(this.dataTemp)
          console.log(data)
          this.selectData = data["order"]
          // console.log(this.selectData)
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }


  //查询工單状态
  doingForm() {
    console.log(this.radioValue);

    this.getDoingData()
    // 选中
    // if (!data.checked) {
    //   console.log(data);

    // const addData = this.dataTemp.filter(res => res['status'] === data.select);
    // this.selectData = this.selectData.concat(addData);
    // console.log(this.selectData)
    // }
    // 未选中
    // if (data.checked) {
    //   console.log(data);

    //   // const deleteData = this.selectData.filter(res => res['status'] === data.select);
    //   // this.selectData = this.selectData.filter(item => !deleteData.some(ele => ele['status'] === item['status']));
    //   // console.log(this.selectData)
    // }
  }

  //查询工件信息
  collapse(item, key) {
    // console.log(key)
    // console.log(item.expand);
    // console.log(this.selectData)
    this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.selectData[key].union_order, "status": 0, })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok' && data['order'].length > 0) {
          this.workData[key] = data['order'];
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //取消工單
  handleCancel() {
    this.isVisible = false;
    this.auditRemark2 = "";
  }
  //确定取消按钮
  handleOk() {
    // debugger
    if (this.auditRemark2) {
      this.isOkLoading = true;
      this.isVisible = false;
      this.isOkLoading = false;
      this.axios.axiosPost('UpdateUnionOrder2', { 'unionorder': this.updateData.union_order, 'name1': 'status', 'newValue1': '2', 'name2': 'cancel_remark', 'newValue2': this.auditRemark2, })
        .then((data) => {
          console.log(data)
          // debugger
          if (data['result'] === 'ok') {
            this.getDoingData();
          }
        })
    } else {
      alert("未填寫刪除工單的原因")
    }

  }
  showModal(item) {
    this.isVisible = true;
    this.updateData = item;
  }

  //点击添加19码
  addCode19(item) {
    console.log(item)
    this.updateData = item;
    if (item.code19) {
      this.first = item.code19.split(',')[0];
      this.tail = item.code19.split(',')[1];
      if (this.first == "/" && item.toolway == "維修") {
        alert("維修工件不可修改十九碼")
      } else {
        this.add19code = true;
      }
    } else {
      this.add19code = true;
    }
  }
  //确定添加19码
  add19CodeOk() {
    if (this.first != "/") {
      console.log(this.first.length, this.tail.length);
      if (this.first.length !== 19 || this.tail.length !== 19) {
        alert('19碼必須為19位');
        this.add19code = true;
      } else {
        let re = /^[0-9]+.?[0-9]*$/;
        if (!re.test(this.first.substr(16, 3))) {
          alert('後三位必須為數字');
          this.add19code = true;
          return;
        }
        let A = this.first.substr(0, 16);//first前15位
        let a = parseInt(this.first.substr(16, 3));//first后4位
        let B;
        let b;
        if (this.tail === '') {
          B = '';
          b = 0;
        } else {
          B = this.tail.substr(0, 16);
          b = parseInt(this.tail.substr(16, 3));
        }
        console.log(a, b)
        // 判断前15位是否一致
        if (A === B) {
          debugger
          //首位19码必须小于末尾19码
          if (a <= b) {
            this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'code19', 'newValue': this.first + ',' + this.tail })
              .then((data) => {
                console.log(data)
                if (data['result'] === 'ok') {
                  this.getDoingData();
                  this.add19code = false;
                  this.show19code = false;
                } else if (data['result'] === 'error') {
                  this.show19code = true;
                  this.newCode19 = data['code19'];
                  this.add19code = true;
                }
              })
          }
        } else {
          this.add19code = true;
          alert("输入的首尾19码前16位不一致")
        }
        this.first = '';
        this.tail = '';
      }
    } else {
      console.log(this.first + ',' + this.tail);

      this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'code19', 'newValue': this.first + ',' + this.tail })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            this.getDoingData();
            this.add19code = false;
            this.show19code = false;
          } else if (data['result'] === 'error') {
            this.show19code = true;
            this.newCode19 = data['code19'];
            this.add19code = true;
          }
        })
    }

  }

  //取消添加19码
  CancelAdd19Code() {
    this.add19code = false;
    this.first = ""
    this.tail = ""
  }

  //取消指派工程师
  CancelAddEngineer() {
    this.addEngineer = false;
    this.zjtypeof = null;
  }
  //确定指派工程师
  AddEngineerOK() {

    console.log(this.zjtypeof)
    console.log(this.clickName.delivery_date);
    console.log(this.clickName.union_order);


    // 设计期限
    this.designDate = this.datePipe.transform(this.designDate, 'yyyy-MM-dd');

    if (this.designDate == null || this.designDate == "") {
      alert("未填寫設計期限")
    } else if (this.estimate_time == null || this.estimate_time == "") {
      alert("未填寫預計時間")
    } else if (this.zjtypeof) {
      // this.axios.axiosPost("DeleteTask", { unionorder: this.clickName.union_order }).then((data) => {
      //   console.log(data)
      //   if (data["result"]) {
      //     this.axios.axiosPost("AddTask", { name: this.clickName.union_order, type: this.zjtypeof, delivery_date: this.clickName.delivery_date, gstype: this.leix }).then((data) => {
      //       console.log(data);
      //       if (data["result"] == "error") {
      //         alert("排班系統添加失敗：" + data["description"])
      //       }
      //       this.zjtypeof = null;
      //     })
      //   }
      // })

      this.estimate_time = Number(this.estimate_time).toFixed(1);
      this.axios.axiosPost('UpdateUnionOrder2', {
        'unionorder': this.clickName.union_order,
        'name1': 'engineer', 'newValue1': this.selectName2,
        'name2': 'design_end_date', 'newValue2': this.designDate,
        'name3': 'estimate_time', 'newValue3': this.estimate_time,
        // "name4": "gstype", "newValue4": this.leix
      })
        .then((data) => {
          this.CancelAddEngineer();
          console.log(data)
          if (data['result'] === 'ok') {
            // this.getDoingData();
            let namelist = "";
            for (let i = 0; i < this.selectName2.length; i++) {
              namelist += this.selectName2[i] + ","
            }
            console.log(namelist.substring(0, namelist.length - 2));
            this.selectData[this.gcsindex].engineer = namelist.substring(0, namelist.length - 1)
            this.selectData[this.gcsindex].design_end_date = this.designDate
            this.selectData[this.gcsindex].estimate_time = this.estimate_time

            // 发送邮件
            this.mailParamsForAssign.emp = this.engineerJobNo;
            this.mailParamsForAssign.empAddress = this.engineerMail;

            this.axios.axiosPost('SendEmail', this.mailParamsForAssign).then((data) => {
              if (data['result'] === 'ok') {
                console.log("SendEmailSuccessfully!");
              }
            }).finally(() => {
              // 每次指定完毕后，重置数组，避免影响下次指定
              this.engineerJobNo = []
              this.engineerMail = []
            })
          }
        })
    } else {
      alert("未填寫治具類型")
    }

  }
  CancelAddEngineer2() {
    this.addEngineer2 = false
  }
  AddEngineerOK2() {
    if (this.zjtypeof != this.clickName.Type) {
      this.leix = this.zjtypelist2
    }
    if (this.leix && this.leix !== null) {
      this.axios.axiosPost("DeleteTask", { unionorder: this.clickName.union_order }).then((data) => {
        console.log(data)
        if (data["result"]) {
          this.axios.axiosPost("AddTask", { name: this.clickName.union_order, type: this.zjtypeof, delivery_date: this.clickName.delivery_date, gstype: this.leix }).then((data) => {
            console.log(data);
            this.addEngineer2 = false
            if (data["result"] == "error") {
              alert("排班系統添加失敗：" + data["description"])
            }
          })
        }
      })
      this.axios.axiosPost('UpdateUnionOrder2', {
        'unionorder': this.clickName.union_order,
        "name1": "gstype", "newValue1": this.leix,
        "name2": "Type", "newValue2": this.zjtypeof
      }).then((data) => {
        console.log(data);

      })
    } else {
      alert("未填寫key point")
    }



  }
  show() {
    this.allkeyp = {
      all: 0, sj: 0, jg: 0, er: 0, zj: 0
    }
    if (this.zjtypeof == this.clickName.Type) {
      if (this.clickName.gstype !== "" || this.clickName.gstype) {
        this.leix = this.clickName.gstype.split(",")
      } else {
        this.leix = [];
      }
      this.axios.axiosPost("QueryPaibanInfo", { mode: this.zjtypeof }).then((data) => {
        if (data["result"] == "ok") {
          console.log(data);
          const arr2 = [];
          this.addEngineer2 = true;
          this.engineerData2 = data["order"][0].type;
          this.engineerDataCheckBoox2 = [];
          console.log(data["order"]);
          console.log(this.engineerData2);
          for (var i = 0; i < data["order"][0].type.length; i++) {
            this.engineerDataCheckBoox2.push(false)
            arr2.push(data["order"][0].type[i].type)
          }

          console.log(this.leix);

          if (this.leix.length > 0) {
            for (var i = 0; i < this.leix.length; i++) {
              for (var y = 0; y < data["order"][0].type.length; y++) {
                if (this.leix[i] == data["order"][0].type[y].type) {
                  this.allkeyp.sj += Number(data["order"][0].type[y].time[0].value)
                  this.allkeyp.jg += Number(data["order"][0].type[y].time[1].value)
                  this.allkeyp.er += Number(data["order"][0].type[y].time[2].value)
                  this.allkeyp.zj += Number(data["order"][0].type[y].time[3].value)
                }
              }
              const key2 = arr2.indexOf(this.leix[i])
              if (key2 > -1) {
                this.engineerDataCheckBoox2.splice(key2, 1, true)
              }
            }
            console.log(this.allkeyp.sj, this.allkeyp.jg, this.allkeyp.er, this.allkeyp.zj);

            this.allkeyp.all = this.allkeyp.sj + this.allkeyp.jg + this.allkeyp.er + this.allkeyp.zj;
          }
          console.log(this.engineerDataCheckBoox2);

        }

      })
    } else {
      console.log(this.zjtypeof);
      this.axios.axiosPost("QueryPaibanInfo", { mode: this.zjtypeof }).then((data) => {
        console.log(data);
        if (data["result"] == "ok") {
          console.log(data);

          this.zjtypelist2 = [];
          this.addEngineer2 = true;
          this.engineerData2 = data["order"][0].type;
          this.engineerDataCheckBoox2 = [];
          console.log(data["order"]);
          console.log(this.engineerData2);
          for (var i = 0; i < data["order"][0].type.length; i++) {
            this.engineerDataCheckBoox2.push(false)
          }
          console.log(this.engineerDataCheckBoox2);

        }
      })
    }





  }
  //点击工程师或指派按钮
  addEngine(item, key) {
    this.gcsindex = key;
    this.zjtypelist = [];
    console.log('点击的姓名 \n', item);
    this.clickName = item;
    this.zjtypeof = item.Type;
    if (item.engineer !== '' || item.engineer) {
      this.selectName2 = item.engineer.split(',');
    } else {
      this.selectName2 = [];
    }
    if (item.gstype !== "" || item.gstype) {
      this.leix = item.gstype.split(",")
    } else {
      this.leix = [];
    }
    console.log(this.zjtypeof, this.leix);

    this.designDate = item.design_end_date;
    this.estimate_time = item.estimate_time;

    // this.selectName2 = [];
    this.addEngineer = true;
    this.axios.axiosPost("QueryWorkhour").then((data) => {
      console.log(data);
      this.zjtypelist = [];
      if (data["result"] == "ok") {
        for (let i = 0; i < data["order"].length; i++) {
          this.zjtypelist.push(data["order"][i]["type"])
        }
        // console.log(this.zjtypelist);

      }
    })
    this.axios.axiosPost('QueryUser', { 'level': 1, "filter": "電控工程師", "filter2": "機構工程師" })
      .then((data) => {
        if (data['result'] === 'ok') {
          this.engineerData = data['order'];
          // console.log('engineerData: \n',this.engineerData);

          const arr = [];
          this.engineerDataCheckBoox = [];
          for (let k = 0; k < this.engineerData.length; k++) {
            arr.push(this.engineerData[k].name)
            // console.log(this.engineerData[k].name)
            this.engineerDataCheckBoox.push(false);
          }

          // 弹出以后 显示哪些人被选中
          console.log(this.selectName2)
          if (this.selectName2.length > 0) {
            // debugger
            for (let i = 0; i < this.selectName2.length; i++) {
              const key = arr.indexOf(this.selectName2[i]);
              console.log(key)
              if (key > -1) {
                this.engineerDataCheckBoox.splice(key, 1, true)
                console.log(this.engineerDataCheckBoox)
              }
            }
          }

          // 准备好邮件发送的内容
          this.mailParamsForAssign.type = 'S2';
          this.mailParamsForAssign.WorkOrder = item.union_order;
          this.mailParamsForAssign.factory = item.factory;
          this.mailParamsForAssign.name = item.name;
          this.mailParamsForAssign.machine_type = item.machine_type;
          this.mailParamsForAssign.quantity = item.quatity;
          this.mailParamsForAssign.toolway = item.toolway;
          this.mailParamsForAssign.delivery_date = item.delivery_date;
        }
      })

  }
  selEngineer2(data, key) {
    // console.log(key);
    // console.log(this.engineerDataCheckBoox2);
    // console.log(data);


    if (this.engineerDataCheckBoox2[key]) {
      this.engineerDataCheckBoox2.splice(key, 1, false);

      this.allkeyp.sj = (Number(Number(this.allkeyp.sj).toFixed(4)) * 10000 - Number(Number(data["time"][0].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.jg = (Number(Number(this.allkeyp.jg).toFixed(4)) * 10000 - Number(Number(data["time"][1].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.er = (Number(Number(this.allkeyp.er).toFixed(4)) * 10000 - Number(Number(data["time"][2].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.zj = (Number(Number(this.allkeyp.zj).toFixed(4)) * 10000 - Number(Number(data["time"][3].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.all = Number(this.allkeyp.sj) + Number(this.allkeyp.jg) + Number(this.allkeyp.er) + Number(this.allkeyp.zj);
    } else {
      this.engineerDataCheckBoox2.splice(key, 1, true);
      this.allkeyp.sj = (Number(Number(this.allkeyp.sj).toFixed(4)) * 10000 + Number(Number(data["time"][0].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.jg = (Number(Number(this.allkeyp.jg).toFixed(4)) * 10000 + Number(Number(data["time"][1].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.er = (Number(Number(this.allkeyp.er).toFixed(4)) * 10000 + Number(Number(data["time"][2].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.zj = (Number(Number(this.allkeyp.zj).toFixed(4)) * 10000 + Number(Number(data["time"][3].value).toFixed(4)) * 10000) / 10000
      this.allkeyp.all = Number(this.allkeyp.sj) + Number(this.allkeyp.jg) + Number(this.allkeyp.er) + Number(this.allkeyp.zj);
    }
    if (this.zjtypeof == this.clickName.Type) {
      if (this.engineerDataCheckBoox2[key]) {
        this.leix.push(this.engineerData2[key].type);
        console.log(this.leix);

      } else {
        const index = this.leix.indexOf(this.engineerData2[key].type)
        console.log(index);

        if (this.leix.indexOf(this.engineerData2[key].type > -1)) { // 如果selectName2包含要去掉的数据
          console.log("1111");

          this.leix.splice(index, 1)
          console.log(this.leix);

        }
      }
    } else {
      if (this.engineerDataCheckBoox2[key]) {
        this.zjtypelist2.push(this.engineerData2[key].type);
        console.log(this.zjtypelist2);

      } else {
        const index = this.zjtypelist2.indexOf(this.engineerData2[key].type)
        console.log(index);

        if (this.zjtypelist2.indexOf(this.engineerData2[key].type > -1)) { // 如果selectName2包含要去掉的数据
          this.zjtypelist2.splice(index, 1)
          console.log(this.zjtypelist2);

        }
      }
    }

  }
  //选择工程师
  selEngineer(data, key) {

    this.engineerJobNo.push(data.job_no)
    this.engineerMail.push(data.mail)

    // console.log("--------  ------\n", data,this.engineerDataCheckBoox, key)
    // 改变选择项的状态
    const status = this.engineerDataCheckBoox[key];
    console.log(this.engineerDataCheckBoox);

    console.log(status);

    if (status) {
      this.engineerDataCheckBoox.splice(key, 1, false);
    } else {
      this.engineerDataCheckBoox.splice(key, 1, true);
    }
    console.log(this.engineerDataCheckBoox)
    console.log(key)
    if (this.engineerDataCheckBoox[key]) {
      this.selectName2.push(this.engineerData[key].name);
    } else {
      const index = this.selectName2.indexOf(this.engineerData[key].name)
      if (this.selectName2.indexOf(this.engineerData[key].name > -1)) { // 如果selectName2包含要去掉的数据
        console.log('索引 === \n', index)
        this.selectName2.splice(index, 1)
      }
    }
    console.log('################### \n', this.selectName2)
  }
  //定义函数：判断元素是否在数组中
  unique(arr: any) {
    var array = [];
    for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
        array.push(arr[i])
      }
    }
    return array;
  }

  currentPageDataChange(qqq) {

  }

  //点击图标显示此工單的文件信息
  downLoad(infom) {
    this.code19 = infom.code19;
    // debugger
    this.fileInfom = true;
    console.log(infom)
    this.updateData = infom;
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.updateData.union_order, 'workorder': this.updateData.name })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.listOfData = data['files'];
          this.workName = this.updateData.union_order;
          console.log(this.listOfData, this.workName)

        }
      })
  }

  CancelShow() {
    this.fileInfom = false;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
  }

  //主管审核
  ClickAudit(data) {
    this.addAudit = true;
    this.fileStatus = data.file_status;
    this.id = data.id;
    this.filePath = data.file_path;
    console.log('=============== \n', data, this.id);
  }

  //取消审核
  CancelAudit() {
    this.addAudit = false;
    this.unionorderer = "";
    this.auditRemark = "";
  }

  //确定审核按钮
  auditOk() {
    // if (this.code19) {
      this.isOkLoadingAudit = true;
      this.addAudit = false;
      this.isOkLoadingAudit = false;
      // debugger
      let index = this.auditRemark.trim().indexOf('ok');//判断是否含有此值
      if (index === 0) {
        this.fileStatus = 1;//审核通过
        // // 审核通过  后修改工單状态  从设计取消 添加到编程
        // console.log(this.workName, "修改的这个工單")
        // this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.workName, "name1": "stage", "newValue1": 0, "stageValue": 0, "newValue12": 1, "stageValue2": 1 }).then((data) => {
        //   console.log(data, "工單状态修改成功了")
        // })
        // // 审核通过  后修改工件状态  从设计取消 添加到编程
        // this.axios.axiosPost("UpdateWorkOrder", { "unionorder": this.workName, "status": 0, "status2": 1 }).then((data) => {
        //   console.log(data, "工件状态为0的，修改成功了")
        // })
      } else {
        this.fileStatus = 2;//已退回
      }
      console.log(this.id)
      this.axios.axiosPost('UpdateWorkFile', {
        'id': this.id,
        'name': 'file_status', 'newValue': this.fileStatus,
        'name2': 'remark', 'newValue2': this.auditRemark.trim()
      })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            // debugger
            this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.updateData.union_order, 'workorder': this.updateData.name })
              .then((data) => {
                console.log(data)
                if (data['result'] === 'ok') {
                  this.listOfData = data['files'];
                  this.workName = this.updateData.union_order;
                  console.log(this.listOfData, this.workName)
                }
              })
            // if (this.fileStatus === 1) {
            //   this.axios.axiosPost('ParseBOMFile', { 'filepath': this.filePath, 'action': 'check' })
            //     .then((data) => {
            //       console.log(data)
            //       if (data['result'] === 'ok') {
            //         // this.QueryWorkOrder(key);
            //       }
            //     })
            // }
          }
        })
      this.getDoingData();
    // } else {
    //   alert("該條工單未添加19碼")
    // }
  }
  //填写审核备注
  handleChange(checked: boolean, tag: string): void {
    // this.selectedTags = [];
    // if(checked) {
    //   this.selectedTags.push(tag);
    // } else {
    //   this.selectedTags = this.selectedTags.filter(t => t !== tag);
    // }
    //   console.log(this.selectedTags);
    // this.auditRemark = this.selectedTags[0]['value'];//赋值
    var msg = tag['value'];
    console.log(tag)
    console.log(this.auditRemark)

    if (msg != "ok") {
      console.log(this.auditRemark.indexOf("ok"))
      if (this.auditRemark.indexOf("ok") == 0) {
        console.log("存在")
        this.auditRemark = this.auditRemark.substring(2)
        console.log(this.auditRemark)

      }
      // console.log(this.auditRemark.indexOf(msg))
      if (this.auditRemark.length > 0) {
        var index = this.auditRemark.indexOf(msg);
        if (index >= 0) {
          var temp = this.auditRemark.split(msg).join('');
          while (temp.length > 0 && temp[0] == ' ') {
            temp = temp.substr(1);
          }
          while (temp.length > 0 && temp[temp.length - 1] == ' ') {
            temp = temp.substr(0, temp.length - 1);
          }
          this.auditRemark = temp.replace('  ', ' ');
        }
        else {
          this.auditRemark += ' ' + msg;
        }
      }
      else {
        this.auditRemark = msg;
      }
    } else {
      this.auditRemark = msg;
    }
  }


  //下载文件
  downLoadFile(data) {
    console.log(data)
    // debugger
    this.fileName = data.file_name;
    this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
    console.log(this.fileName, this.link)
  }

  handleFileCancel() {
    this.isFileVisible = false;
  }

  //删除文件信息
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data)
    this.id = data.id;
  }

  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          let listData = this.listOfData.filter(res => res['id'] !== this.id)
          this.listOfData = listData;
        }
      })
  }

  // 添加單價
  addPrice(item, key) {
    // console.log(key);

    this.keydanjia = key
    this.updateData = item;
    this.addprice = true;
    this.price = item.price;
    console.log(this.price);
  }
  CancelCheck() {
    this.addprice = false;
    this.price = '';
  }
  CheckOk() {
    // debugger
    this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'price', 'newValue': this.price })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          // this.getDoingData();
          this.selectData[this.keydanjia].price = this.price
          // console.log(this.selectData);
          // console.log(this.keydanjia);

          this.addprice = false;
          this.price = '';
        }
      })
  }


  //点击工單号显示CNC
  // showCNC(item) {
  //   console.log(item)
  //   const data = {};
  //   data['union_order'] = item.union_order;
  //   console.log(data['union_order'])
  //   this.router.navigate(['/CNC', data])
  //   // {queryParams: {refersh: new Date().getTime()}}
  // }
  // 送出
  send(item) {

    // console.log(item)
    // console.log(item.engineer)
    this.ununun = item.union_order;
    if (item.engineer == "") {
      alert("未指派工程師")
    } else {
      if (!item.priority) {
        if (item.price) {
          console.log("存在")
          this.axios.axiosPost("DesignSendout", { "unionorder": item.union_order }).then((data) => {
            console.log(data)
            if (data["result"] == "ok") {
              this.titlett = "確認送出這個工單嗎？"
              this.isSendVisible = true;

              // 准备邮件发送的参数
              this.mailParamsForSend.type = 'S3';
              this.mailParamsForSend.WorkOrder = item.union_order;
              this.mailParamsForSend.factory = item.factory;
              this.mailParamsForSend.name = item.name;
              this.mailParamsForSend.machine_type = item.machine_type;
              this.mailParamsForSend.quantity = item.quatity;
              this.mailParamsForSend.toolway = item.toolway;
              this.mailParamsForSend.delivery_date = item.delivery_date;
            } else if (data["result"] = "error") {
              if (data["description"]) {
                this.titlett = data["description"]
              } else {
                this.titlett = "暫時無法送出"

              }
              this.isSendVisible = true;
            } else {
              this.isSendVisible = true;
              this.titlett = "暫時無法送出"
            }
          })
        } else {
          this.isSendVisible = true;
          this.titlett = "未填寫單價"
        }
      } else {
        this.isSendVisible = true;
        this.titlett = "該工單未停止計時"
      }
    }

  }
  sendOk() {
    this.isSendVisible = false
    if (this.titlett == "確認送出這個工單嗎？") {
      let time;
      let n = new Date().getFullYear().toString();
      let y = (new Date().getMonth() + 1) >= 10 ? (new Date().getMonth() + 1).toString() : "0" + (new Date().getMonth() + 1).toString();
      let r = new Date().getDate() >= 10 ? new Date().getDate().toString() : "0" + new Date().getDate().toString();
      time = n + "-" + y + "-" + r
      console.log(time);

      console.log(this.ununun)
      this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.ununun, "name1": "stage", "newValue1": 0, "name2": "sheji_endtime", "newValue2": time, "stageValue": 0, "newValue12": 1, "stageValue2": 1 }).then((data) => {
        console.log(data, "工單状态修改成功了,取消了当前工單状态")
        this.getDoingData();

      })

      this.axios.axiosPost('UpdateWorkOrder', {
        'unionorder': this.ununun, 'status': 1, "tuidan": 0
      })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {

            // 发送邮件
            this.axios.axiosPost('SendEmail', this.mailParamsForSend).then((data) => {
              if (data['result'] === 'ok') {
                console.log("SendEmailSuccessfully!");
              }
            }).finally(() => {
              // 每次指定完毕后，重置数组，避免影响下次指定
              this.engineerJobNo = []
              this.engineerMail = []
            })

          }
        })

    } else {
      alert("送出失敗")
    }
  }
  handleSendCancel() {
    this.isSendVisible = false
  }
  // 选择类型
  tpyeof(result: Date): void {
    console.log('onChange: ', result);
  }
  CancelCheck2() {
    this.addprice2 = false
  }
  CancelCheck3() {
    this.addprice3 = false
  }
  CheckOk2() {
    this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'quatity', 'newValue': this.price2 })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.getDoingData();
          this.addprice2 = false;
          this.price2 = '';
        }
      })
  }
  CheckOk3() {
    this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'delivery_date', 'newValue': this.price3 })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.getDoingData();
          this.addprice3 = false;
          this.price3 = '';
        }
      })
  }
  addPrice2(item) {
    this.updateData = item;
    this.addprice2 = true;
    this.price2 = item.quatity
  }
  addPrice3(item) {
    this.updateData = item;
    this.addprice3 = true;
    this.price3 = item.delivery_date

  }
  download2() {
    this.axios
      .axiosPost("QueryUnionOrder")
      .then((data) => {
        console.log(data);
        this.listdata2 = data["order"];
        console.log(this.listdata2);
        if (this.listdata2.length == 0) {
          alert("暫無數據");
        } else {
          let dowmTimeList = [];
          let exportlist = [];
          for (let i = 0; i < this.listdata2.length; i++) {
            exportlist.push({
              工聯單號: this.listdata2[i].union_order,
              廠區: this.listdata2[i].factory,
              機種: this.listdata2[i].machine_type,
              治具名稱: this.listdata2[i].name,
              數量: this.listdata2[i].quatity,
              十九碼: this.listdata2[i].code19,
              制作方式: this.listdata2[i].toolway,
              單價: this.listdata2[i].price,
              填單人姓名: this.listdata2[i].apply_person,
              申請部門負責人: this.listdata2[i].applyDeptPIC,
              送貨區域: this.listdata2[i].delivery_addr,
              治具交期: this.listdata2[i].delivery_date
            })
          }
          exportlist.forEach((row: any) => {
            dowmTimeList.push(Object.values(row));
            // dowmTimeList.push(
            //   {
            //     工聯單號: row.union_order,
            //     廠區: row.factory,
            //     機種: row.machine_type,
            //     治具名稱: row.name,
            //     數量: row.quatity,
            //     十九碼: row.code19,
            //     制作方式: row.toolway,
            //     單價: row.price,
            //     填單人姓名: row.apply_person,
            //     申請部門負責人: row.applyDeptPIC,
            //     送貨區域: row.delivery_addr,
            //     治具交期: row.delivery_date
            //   }
            // );
          });
          // console.log(dowmTimeList);

          let head = [
            "工聯單號",
            "廠區",
            "機種",
            "治具名稱",
            "數量",
            "十九碼",
            "制作方式",
            "單價",
            "填單人姓名",
            "申請部門負責人",
            "送貨區域",
            "治具交期"
          ];
          let reportData = {
            title: "所有工單",
            data: dowmTimeList,
            headers: head,
          };
          this.excel.exportExcel99(reportData);
        }
      })
      .catch((err) => {
        console.log(err);
      });
    this.listdata2 = [];
  }

}
